<template>
  <BasicModal title="行程编辑" @register="registerModal" destroyOnClose
              :canFullscreen="false" :centered="true" :maskClosable="false" :scrollbar="{native: false}"
              :width="'95%'" :okButtonProps="{loading: loading}" @ok="handleSubmit" @cancel="onCancel"
              :bodyStyle="{height:'calc(100vh - 100px)', overflowY:'auto'}"
  >
  <div class="input" style="zoom: 1; min-width:1200px; padding: 0 10px 10px;" :style="{height:'calc(100vh - 120px)', overflowY:'auto'}">
    <a-form ref="formRef" :model="cmsArticle" :rules="validatorRules">
    <table class="main_table addTour" width="100%">
      <tbody>
      <colgroup><col width="10%"/><col width="70%"/><col width="20%"/></colgroup>
      <tr>
        <td align="right" class="w-120px"><label class="Validform_label">0、所属栏目：</label></td>
        <td class="value" id="labbels">
          <!--t:dictSelect id="state" field="state" typeGroupCode="stateType" hasLabel="false" defaultVal="cmsArticle.state == 1 ? 1 : 0" type="select" extendJson="{style:'width:100px;height:30px;'" readonly="readonly"></t:dictSelect-->
          <div class="w-285px float-left h-34px leading-34px">
            <ApiTreeSelect
              :api="menuList"
              :value="cmsArticle.menuentityId"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :fieldNames="{ children: 'children', label: 'name', key: 'id', value: 'id', selectable: 'selectable' }"
              :treeDefaultExpandAll="true"
              allowClear
              style="width: 280px"
              @select="onSelect"
            >
            </ApiTreeSelect> 
          </div>
          <div class="w-55px float-left h-34px leading-34px">
            <JDictSelectTag v-model:value="cmsArticle.state" dictCode="stateType" :disabled="true"/>
          </div>
          <div class="w-50px float-left h-34px leading-34px margin-left-20px text-right">类型：</div>
          <div class="float-left h-34px leading-34px w-100ppx">
            <JDictSelectTag v-model:value="labelAarry" dictCode="labbelType" @change="setLabels" type="checkbox" />
          </div>
        </td>
        <td class="w-380px"><span class="red">* 网红、纯玩、主推，只可选择其中两项目</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label" style="height: 50px">1、收客计调：</label></td>
        <td>
          <div class="float-left h-34px leading-34px margin-left-20px margin-right-10px" >
            <JDictSelectTag 
              type="select" 
              v-model:value="cmsArticle.ddlx" 
              dictCode="ddlxType@ddlxUser" 
              placeholder="请选择" 
              :dropdownStyle="{ width: '120px', overflow: 'auto' }"
              :styler="{width: '90px', marginRight: '5px'}"
              @change="loadSkrOptions"
            />

            <a-select v-model:value="cmsArticle.skrsArray"  allowClear 
              mode="multiple"
              maxTagCount='4'
              :showSearch="true" 
              :numberToString="true"
              :style="{width: '400px'}"
            >
              <template v-for="item in cacheData.skrOptions" :key="`${item.value}`">
                <a-select-option :value="item.value">
                  <span>{{ item.label }}</span>
                </a-select-option>
              </template>
            </a-select>

          </div>
        </td>
        <td><span class="red">* 直客不显</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">2、线路标题：</label></td>
        <td>
          <div class="w-50px float-left h-34px leading-34px">
            <a-form-item name="number">
            <a-input type="text" style="width:45px;margin-right:10px" v-model:value="cmsArticle.number" @blur="doOrderNumber" placeholder="编号"/>
            </a-form-item>
          </div>
          <div class="w-105px float-left h-34px leading-34px">
            <a-form-item name="sub">
            <a-input type="text" style="width:100px; margin-right:10px" v-model:value="cmsArticle.sub" placeholder="短标题" />
            </a-form-item>
          </div>
          <div class="w-535px float-left h-34px leading-34px">
            <a-form-item name="title">
            <a-input type="text" style="width:525px;margin-right:10px" v-model:value="cmsArticle.title" placeholder="长标题" />
            </a-form-item>
          </div>
          <div class="w-50px float-left h-34px leading-34px text-right">排序：</div>
          <div class="w-70px float-left h-34px leading-34px">
            <a-input type="text" v-model:value="cmsArticle.orders" style="width:60px;" />
          </div>
        </td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">3、行程特色：</label></td>
        <td><JEditor :height="260" :width="800" v-model:value="cmsArticle.summary"></JEditor></td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">4、标题图片：</label></td>
        <td>
          <div class="inPic">
            <input type="hidden" id="headPhotoIds" name="headPhotoIds" nullmsg="请添加标题图片" value="" datatype="*" />
            <input type="hidden" id="image_href" name="image_href" value="" />
            <JImageUpload
              bizPath="photos"
              :params="{articleId: cacheData.articleId}"
              :fileMax="4"
              :addUrl="cmsPhotoUploadUrl"
              :delUrl="cmsPhotoDelete"
              v-model:value="cacheData.photos"
            >
            </JImageUpload>
          </div>
        </td>
        <td><span class="red">*</span>推荐图片尺寸，宽1000px，高=560px | 宽800px，高=615px; 上传图片大小，限制需要小于 300kb;  </td>
      </tr>
      <tr id="tr5">
        <td align="right"><label class="Validform_label">5、日期价格：</label></td>
        <td>
          <CalendarPrice :articleId="cacheData.articleId"></CalendarPrice>
        </td>
        <td></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">6、收客须知：</label></td>
        <td>
          <JEditor :height="260" :width="800" v-model:value="cmsArticle.instructions"></JEditor>
        </td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">7、行程天数：</label></td>
        <td>
          行程
          <a-input type="text" v-model:value="cmsArticle.days" class="w30 grayBC" onkeyup="value=value.replace(/[^\d]/g,'')" onblur="value=value.replace(/[^\d]/g,'');" autocomplete="off" :readonly="true" datatype="n"/> 天
          提前
          <a-input type="text" v-model:value="cmsArticle.isGuestEnd" class="w30" datatype="n" :readonly="true"/> 日停止收客
        </td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">8、详细行程：</label></td>
        <td style="min-height:224px">
          <CmsRoutes :articleId="cacheData.articleId" :days="cacheData.schedulesDay" @change="handleCmsRoutesChange"></CmsRoutes>
        </td>
        <td>请在有效景点行程中上传景点图片，否则无法通过审核。</td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">9、费用包含：</label></td>
        <td>
          <JEditor :height="260" :width="800" v-model:value="cmsArticle.expenseContain"></JEditor>
        </td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">10、费用不含：</label></td>
        <td>
          <JEditor :height="300" :width="800" v-model:value="cmsArticle.expenseNcontain"></JEditor>
        </td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">11、注意事项：</label></td>
        <td>
          <JEditor :height="300" :width="800" v-model:value="cmsArticle.notice"></JEditor>
        </td>
        <td><span class="red">*</span></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">12、特别提示：</label></td>
        <td>
          <JEditor :height="300" :width="800" v-model:value="cmsArticle.warmPrompt"></JEditor>
        </td>
        <td></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">13、购物安排：</label></td>
        <td>
          <JEditor :height="300" :width="800" v-model:value="cmsArticle.shoppingExplanation"></JEditor>
        </td>
        <td></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">14、自费补充协议：</label></td>
        <td>
          <JEditor :height="300" :width="800" v-model:value="cmsArticle.selfpayingExplanation"></JEditor>
        </td>
        <td></td>
      </tr>
      <tr>
        <td align="right"><label class="Validform_label">15、当地接待社信息：</label></td>
        <td>
          <JEditor :height="300" :width="800" v-model:value="cmsArticle.receptionExplanation"></JEditor>
        </td>
        <td></td>
      </tr>
      <tr style="height: 50px">
        <td align="right"><label class="Validform_label">16、行程文档：</label></td>
        <td>
          <div class="w-800px min-h-30px" style="border: 1px #e5e7eb solid">
          <JUpload text="附件上传" color="success" size="small" bizPath="files"
            :data="{articleId: cacheData.articleId}"
            :action="cmsFilesUploadUrl"
            :delUrl="cmsFilesDelete"
            :returnUrl="false"
            v-model:value="cacheData.files"
          >
          </JUpload>
          </div>
        </td>
        <td><span class="red">* 直客不显</span></td>
      </tr>
      </tbody>
    </table>
    </a-form>
  </div>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, reactive, unref, computed } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { useMessage } from "/@/hooks/web/useMessage";
import { list as menuList } from "/@/views/weixin/menu/menu.api";
import { ApiTreeSelect } from '/@/components/Form';
import { JEditor } from '/@/components/Form';
import { CalendarPrice } from "/@/views/weixin/article/components";
import {
  queryById,
  save,
  cmsPhotoList,
  cmsPhotoUploadUrl,
  cmsFilesUploadUrl,
  cmsFileList,
  cmsPhotoDel,
  cmsFilesDel,
  skrsSelect
} from "/@/views/weixin/article/artticle.api";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import JImageUpload from "/@/components/Form/src/jeecg/components/JImageUpload.vue";
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import CmsRoutes from "/@/views/weixin/article/modules/CmsRoutes.vue";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

const loading  = ref(false);
const $message = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
let isReload   = ref<boolean>(false);
let labelAarry = ref<[]>([]);
let cacheData  = reactive<any>({
  articleId    : "",  //文章数据库编号
  schedulesDay : "",  //行程天数
  photos : [],
  routes : [],
  files: [],
  skrOptions: []
})

//主表数据
let cmsArticle = reactive<any>({})
//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  await nextTick(() => {
    cmsArticle = reactive<any>({})
    // cacheData.articleId    = '';
    // cacheData.schedulesDay = '';
  });
  await init(data);
});

function init(data) {
  if (!data.id) {
    alert("行程编号不能为空!");
    return;
  }
  initData(data);
}

/**
 * 初始化界面
 */
async function initData(data) {
  loading.value = true;
  let params = { id: data.id };
  await queryById(params).then((res) => {
    try {
      //console.info("initData@@@@",res.success)
      if (res.success != true) {
        //$message.warning(res.message);
        return false;
      }
      let result = res.result;
      //1、主表 cmsArticle
      Object.assign(cmsArticle, result);

      //收客人
      let skrs = cmsArticle.skrIds && cmsArticle.skrIds.split(",").filter(item => item);
      cmsArticle.skrsArray = skrs || [];

      cacheData.articleId = cmsArticle.id;
      cacheData.schedulesDay = cmsArticle.days;
      //标签
      if (cmsArticle.labels) {
        labelAarry.value = cmsArticle.labels.split(",").filter(i => i && i.trim());
      } else {
        labelAarry.value = [];
      }

      //2、顶部图片
      initCmsPhoto();

      //3、收客人
      loadSkrOptions();

      //3、行程
      //initCmsRoutes();

      //4、附件下载
      initCmsFile();

      //5、价格排期
      //cmsSchedule();

      //setLabels();

    } catch (e) {
      alert(e);
    } finally {
      loading.value = false;
    }
  })
}

/**
 * 图片列表加载完成触发
 */
function initCmsPhoto() {
  let params = {articleId: cacheData.articleId};
  cmsPhotoList(params).then((list) => {
    try {
      //Object.assign(cacheData.cmsPhotos, list);
      if (list) {
        let headerPic = list.map((item) => {
          return {
            id: item.id,
            name: item.name,
            realpath: item.realpath
          };
        });
        //console.info("initCmsPhoto@@", list)
        cacheData.photos = headerPic;
      } else {
        //console.info('initCmsPhoto() 无数据返回。。');
        cacheData.photos = [];
      }
    } catch (e) {
      alert("initCmsPhoto: " + e);
      return false;
    }
  })
}

/**
 * 图片列表加载完成触发
 */
function initCmsFile() {
  let params = {articleId: cacheData.articleId};
  cmsFileList(params).then((list) => {
    try {
      if (list) {
        let files = list.map((item) => {
          return {
            id: item.id,
            fileName: item.name,
            filePath: item.realpath
          };
        });
        cacheData.files = files;
      } else {
        //console.error('initCmsFile() 无数据返回 ');
        cacheData.files = [];
      }
    } catch (e) {
      alert("initCmsFile(): " + e);
      return false;
    }
  })
}

function cmsPhotoSave(fileList) {
  //console.log("cmsPhotoSave", fileList)
}

function cmsPhotoDelete(params) {
  cmsPhotoDel(params)
}

/**
 * 附件列表
 * @returns
 */
function buildCmsAttachment(photo, ul) {
  let photo_id = photo['id'], photo_name = photo['attachmenttitle'], photo_path = photo['realpath'];
  let itm = ['<li cache-id="' + photo_id + '">'];
  itm.push('<span class="routePhotoItem" title=\"点击下载\">');
  itm.push('<a href=\"download.do?getDownloadFile&fileName=' + photo_path +'\" >' + photo_name + '</a>');
  itm.push('</span>');
  itm.push('<span class="routePhotoDel" onclick="delUpdateFile(\'' + photo_id + '\')" title=\"点击删除\">X</span>');
  itm.push('</li>');
  //$(itm.join('')).appendTo(ul);
}

const validatorRules = {
  menuentityId: [{ required: true, message: '栏目分类不能为空', trigger: 'blur' }],
  ddlx: [{ required: true, message: '', trigger: 'blur' }],
  number: [{ required: true, message: '', trigger: 'blur' }],
  sub: [{ required: true, message: '', trigger: 'blur' }],
  title: [{ required: true, message: '', trigger: 'blur' }],
};

//表单提交事件
const formRef = ref();
async function handleSubmit() {
  // qindl 2023-04-26
  // formRef.value.validate()
  // .then(async () => {})
  // .catch((error: ValidateErrorEntity<any>) => {
  //   console.log('error', error);
  // });

  await formRef.value.validateFields();

  loading.value = true;
  try {
    setModalProps({confirmLoading: true});
    //const values = await validate();
    //console.info("handleSubmit@@", cmsArticle.routes)
    cmsArticle.skrs = ''
    if (cmsArticle.skrsArray.length > 0) {
      cmsArticle.skrs = cmsArticle.skrsArray.join(',');
    } 
    save(cmsArticle).then((res) => {
      if (res.success) {
        $message.createMessage.success(res.message);
        //关闭弹窗
        onCancel()
        closeModal();
        emit("success")
      } else {
        $message.createMessage.warning(res.message);
      }
      loading.value = false;
    });
  } catch (e) {
    console.log(e);
  } finally {
    setModalProps({confirmLoading: false});
  }
}

/**
 * 选中树节点事件
 */
function onSelect(value, node, extra)	 {
  if (node.children && node.children.length > 0) {
    return false;
  }
  //console.info(node.children && node.children.length > 0)
  cmsArticle.menuentityId = value;
}

function setLabels() {
  let mutex = 0;
  let $labbelCheck = labelAarry.value
  for (let i = 0; i < $labbelCheck.length; i++) {
    let v = $labbelCheck[i];//$(cb).val();
    if (",1,5,".indexOf(v) == -1) {
      mutex = mutex + Math.round(v);
    }
  }

  let k = 9 - mutex;
  if (",2,3,4,".indexOf(k) > -1) {
    //$("#labbels #_labbel"+k).attr("disabled", true);
  } else {
    //$("#labbels").find('input:checkbox').attr("disabled", false);
  }
  cmsArticle.labels = labelAarry.value.join(",")
  //console.info(cmsArticle.labels)
}

/**
 * 行程数据变更
 */
function handleCmsRoutesChange(data) {
  cmsArticle.routes = data;
  //console.info("handleCmsRoutesChange@@", unref(cmsArticle.routes[0]))
}

async function onCancel() {
  let o = {
    articleId    : "",  //文章数据库编号
    schedulesDay : "",  //行程天数
    photos : [],
    routes : [],
    files  : [],
    skrsOptions: []
  };
  Object.assign(cacheData, o)
  //console.info("onCancel", cacheData)
}

function doOrderNumber() {
  // var value = cmsArticle.number;
  // if (!value) {
  //   $message.createMessage.warning("2、线路标题-编号：不能为空!")
  //   return false
  // }
  //
  // var reg = new RegExp(/^[A-Z][0-9][0-9]/);
  // if (!reg.test(value)) {
  //   $message.createMessage.warning("2、线路标题-编号：格式不正确，应以大写字母+两位数字；（如：L14）。")
  //   return false;
  // }
}

function cmsFilesDelete(params) {
  cmsFilesDel(params)
}

function loadSkrOptions() {
  console.info("loadSkrOptions", cmsArticle.ddlx)
  if (!cmsArticle.ddlx) {
    cacheData.skrOptions = [];
    return;
  }
  let params = {ddlx: cmsArticle.ddlx};
  skrsSelect(params).then((list) => {
    try {
      if (list) {
        cacheData.skrOptions = list;
      } else {
        //console.error('initCmsFile() 无数据返回 ');
        cacheData.skrOptions = [];
      }
    } catch (e) {
      alert("initCmsFile(): " + e);
      return false;
    }
  })
}

// 获取头像
function getAvatar(item) {
  var face = item.headimgurl;
  if (face) {
    if (face.indexOf("http")>0) {
      return face;
    } 
    return getFileAccessHttpUrl(face)
  }
  return "";
}

// 头像没有获取 用户名前两位
function getAvatarText(item){
  if (item.name) {
    return item.name.substr(0, 1);
  }
  return '';
}

onMounted(async () => {
  console.log('页面渲染完成！');
  // loading.value = false
  // await nextTick(() => {
  //   loading.value = false
  // });
});


</script>

<style lang="less" scoped>
@import "../cmsArticle.css";
.ant-upload-list {
  width: 600px;
  border: 1px red solid;
}
</style>
